using MediatR;
using Medical.Api.Write.Application.Command.BasicManagement.ShelfDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Write.Application.Handler.BasicManagement.ShelfDictionaryHandler
{
    /// <summary>
    /// 删除货架处理器
    /// 处理货架逻辑删除请求，将指定货架标记为已删除状态
    /// </summary>
    public class DeleteShelvesHandler : IRequestHandler<DeleteShelvesCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<Shelves> _shelvesRepository;
        private readonly ILogger<DeleteShelvesHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="shelvesRepository">货架仓储接口</param>
        /// <param name="logger">日志记录器</param>
        public DeleteShelvesHandler(
            IBaseRepository<Shelves> shelvesRepository,
            ILogger<DeleteShelvesHandler> logger)
        {
            _shelvesRepository = shelvesRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除货架请求
        /// </summary>
        /// <param name="request">删除货架命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public Task<ApiResult<bool>> Handle(DeleteShelvesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据ID查找货架记录
                var shelves = _shelvesRepository.GetModel(request.Id);
                if (shelves == null)
                {
                    return Task.FromResult(new ApiResult<bool>
                    {
                        Code = ApiEnums.NotFound,
                        Msg = "货架不存在",
                        Data = false
                    });
                }

                // 执行逻辑删除：将IsDeleted设为true
                shelves.IsDeleted = true;
                shelves.UpdateTime = DateTime.Now;

                var result = _shelvesRepository.Update(shelves);

                return Task.FromResult(new ApiResult<bool>
                {
                    Code = result > 0 ? ApiEnums.Success : ApiEnums.Error,
                    Msg = result > 0 ? "货架删除成功" : "货架删除失败",
                    Data = result > 0
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除货架时发生异常");
                return Task.FromResult(new ApiResult<bool>
                {
                    Code = ApiEnums.Error,
                    Msg = "删除货架时发生错误",
                    Data = false
                });
            }
        }
    }
}